package com.kkwrite.regimen.provider.service.shop;

import java.math.BigDecimal;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

import javax.annotation.Resource;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.data.domain.Example;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import ch.qos.logback.classic.pattern.Util;

import com.kkwrite.regimen.common.constant.SortTypeEnum;
import com.kkwrite.regimen.common.entity.dto.item.ItemDetailDTO;
import com.kkwrite.regimen.common.entity.dto.picture.PictureDTO;
import com.kkwrite.regimen.common.entity.dto.shop.EditShopInDTO;
import com.kkwrite.regimen.common.entity.dto.shop.EditShopOutDTO;
import com.kkwrite.regimen.common.entity.dto.shop.InsertShopEmployeeInDTO;
import com.kkwrite.regimen.common.entity.dto.shop.InsertShopEmployeeOutDTO;
import com.kkwrite.regimen.common.entity.dto.shop.InsertShopOutDTO;
import com.kkwrite.regimen.common.entity.dto.shop.PageableItemDTO;
import com.kkwrite.regimen.common.entity.dto.shop.PageableShopIncomeDTO;
import com.kkwrite.regimen.common.entity.dto.shop.ShopDetailDTO;
import com.kkwrite.regimen.common.entity.dto.shop.ShopIncomeCountDTO;
import com.kkwrite.regimen.common.entity.dto.user.PageableUserDTO;
import com.kkwrite.regimen.common.entity.dto.user.UserOutDTO;
import com.kkwrite.regimen.provider.domain.RegEmployeeDO;
import com.kkwrite.regimen.provider.domain.RegOrderDO;
import com.kkwrite.regimen.provider.domain.RegPictureDO;
import com.kkwrite.regimen.provider.domain.RegShopDO;
import com.kkwrite.regimen.provider.domain.RegShopIncomeDO;
import com.kkwrite.regimen.provider.domain.RegShopItemDO;
import com.kkwrite.regimen.provider.domain.RegUserDO;
import com.kkwrite.regimen.provider.exception.DBNullException;
import com.kkwrite.regimen.provider.exception.ServiceException;
import com.kkwrite.regimen.provider.repository.RegAddressRepository;
import com.kkwrite.regimen.provider.repository.RegEmployeeRepository;
import com.kkwrite.regimen.provider.repository.RegOrderRepository;
import com.kkwrite.regimen.provider.repository.RegPictureRepository;
import com.kkwrite.regimen.provider.repository.RegShopIncomeRepository;
import com.kkwrite.regimen.provider.repository.RegShopItemRepository;
import com.kkwrite.regimen.provider.repository.RegShopRepository;
import com.kkwrite.regimen.provider.repository.RegUserRepository;
import com.kkwrite.regimen.provider.service.BaseServiceImpl;
import com.kkwrite.regimen.provider.service.item.ItemService;
import com.kkwrite.regimen.provider.service.order.OrderService;
import com.kkwrite.regimen.provider.service.picture.PictureService;
import com.kkwrite.regimen.provider.service.user.UserService;

/**
 * 店铺服务
 *
 * @author Soosky Wang
 * @version 1.0.0
 * @date 2018年7月21日 上午9:57:29
 */
@Service("shopService")
public class ShopServiceImpl extends BaseServiceImpl implements ShopService {

    private static final Logger logger = LoggerFactory.getLogger(ShopServiceImpl.class);

    @Resource(name = "regShopRepository")
    private RegShopRepository regShopRepository;

    @Resource(name = "pictureService")
    private PictureService pictureService;

    @Resource(name = "regAddressRepository")
    private RegAddressRepository regAddressRepository;

    @Resource(name = "regShopItemRepository")
    private RegShopItemRepository regShopItemRepository;

    @Resource(name = "itemService")
    private ItemService itemService;

    @Resource(name = "regShopIncomeRepository")
    private RegShopIncomeRepository regShopIncomeRepository;

    @Resource(name = "regUserRepository")
    private RegUserRepository userRepository;

    @Resource(name = "orderService")
    private OrderService orderService;

    @Resource(name = "regPictureRepository")
    private RegPictureRepository regPictureRepository;

    @Resource(name = "regOrderRepository")
    private RegOrderRepository regOrderRepository;

    @Resource(name = "regUserService")
    private UserService userService;

    @Resource(name = "regEmployeeRepository")
    private RegEmployeeRepository regEmployeeRepository;
	/*@Resource(name = "userService")
	private UserService userService;*/

    /**
     * 根据 shopId 查询店铺详情
     *
     * @param shopId
     * @return
     * @throws ServiceException
     */
    @Override
    public ShopDetailDTO getShopDetail(Long shopId) throws ServiceException {
        if (logger.isDebugEnabled()) {
            logger.debug("ShopServiceImpl.getShopDetail(), shopId = {}" + shopId);
        }

        // 查询店铺
        RegShopDO regShopDO = null;
        ShopDetailDTO shopDetailDTO = new ShopDetailDTO();
        try {
            RegShopDO regShopDOParam = new RegShopDO();
            regShopDOParam.setShopId(shopId);
            Optional<RegShopDO> regShopDOResult = regShopRepository.findOne(Example.of(regShopDOParam));
            regShopDO = regShopDOResult.orElseThrow(() -> new NullPointerException());
            BeanUtils.copyProperties(regShopDO, shopDetailDTO, "address", "pictures");
        } catch (Exception e) {
            e.printStackTrace();
            throw new ServiceException(e.getMessage());
        }

        // 查询店铺配图
        try {
            List<PictureDTO> pictures = pictureService.getOwerPictures(regShopDO.getShopId(), (short) 1); // TODO owerType 值写死了
            shopDetailDTO.setPictures(pictures);
        } catch (ServiceException e) {
            e.printStackTrace();
            throw new ServiceException(e.getMessage());
        }

        return shopDetailDTO;
    }

    //店铺项目列表分页接口
    @Override
    public PageableItemDTO queryItemByShopId(Integer page, Integer size,
                                             Long shopId, Integer sortType) throws NumberFormatException,
            ServiceException {

        Sort.Direction direction = Sort.Direction.DESC;
        if (SortTypeEnum.POSITIVE_SEQUENCE.getValue().equals(sortType)) {
            direction = Sort.Direction.ASC;
        }
        Pageable pageable = new PageRequest(page, size, new Sort(direction,
                "gmtCreate"));
        RegShopItemDO regShopItemDo = new RegShopItemDO();
        regShopItemDo.setShopId(shopId);
        Page<RegShopItemDO> pageData = regShopItemRepository.findAll(
                Example.of(regShopItemDo), pageable);

        PageableItemDTO pageableItemDTO = new PageableItemDTO();
        pageableItemDTO.setTotalPages(pageData.getTotalPages());
        pageableItemDTO.setTotalElements(pageData.getTotalElements());
        List<ItemDetailDTO> itemDetailDtoList = new ArrayList<>();
        if (pageData.getContent() != null) {
            pageData.getContent().forEach((recordDo) -> {
                ItemDetailDTO itemDetailDto = itemService.getItemDetail(recordDo.getItemId());
                itemDetailDtoList.add(itemDetailDto);
            });
        }
        pageableItemDTO.setRecordList(itemDetailDtoList);
        System.out.println("店铺项目分页列表：" + pageableItemDTO.toString());
        return pageableItemDTO;
    }

    @Override
    public ShopIncomeCountDTO queryShopIncomeByShopId(Long shopId)
            throws ServiceException {
        List<RegShopIncomeDO> shopIncomeDoList = regShopIncomeRepository
                .findAllByShopId(shopId);
        Double totalIncome = 0.0;
        for (int i = 0; i < shopIncomeDoList.size(); i++) {
            BigDecimal bd1 = new BigDecimal(Double.toString(shopIncomeDoList.get(i).getIncomeAmount()));
            BigDecimal bd2 = new BigDecimal(Double.toString(totalIncome));
            totalIncome = bd1.add(bd2).doubleValue();
        }
        ShopIncomeCountDTO shopIncomeCountDTO = new ShopIncomeCountDTO();
        shopIncomeCountDTO.setShopIncomeTotal(totalIncome);
        System.out.println("店铺收益总数：" + shopIncomeCountDTO.toString());
        return shopIncomeCountDTO;
    }

    //查看店铺邀请明细接口
    @Override
    public PageableUserDTO queryUserByInviterIdShop(Integer page, Integer size,
                                                    Long shopId, Integer sortType) {

        Sort.Direction direction = Sort.Direction.DESC;
        if (SortTypeEnum.POSITIVE_SEQUENCE.getValue().equals(sortType)) {
            direction = Sort.Direction.ASC;
        }
        Pageable pageable = PageRequest.of(page, size, new Sort(direction, "gmtCreate"));
        RegUserDO regUserDO = new RegUserDO();
        regUserDO.setInviterId(shopId);
        //1是用户邀请，2是店铺邀请
        regUserDO.setInviteFlag(2);
        Page<RegUserDO> pageData = userRepository.findAll(Example.of(regUserDO), pageable);
        PageableUserDTO pageableUserDto = new PageableUserDTO();
        pageableUserDto.setTotalPages(pageData.getTotalPages());
        pageableUserDto.setTotalElements(pageData.getTotalElements());
        List<UserOutDTO> userOutDtoList = new ArrayList<>();
        pageData.getContent().forEach((recordDo) -> {
            UserOutDTO userOutDto = new UserOutDTO();
            BeanUtils.copyProperties(recordDo, userOutDto);
            userOutDtoList.add(userOutDto);
        });
        pageableUserDto.setRecordList(userOutDtoList);
        if (pageableUserDto.getRecordList() != null) {
            for (int i = 0; i < pageableUserDto.getRecordList().size(); i++) {
                System.out.println(i + "店铺邀请明细List:"
                        + pageableUserDto.getRecordList().get(i).toString());
            }
        }
        return pageableUserDto;
    }

    @Override
    public PageableShopIncomeDTO queryShopIncome(Integer page, Integer size,
                                                 Long shopId, Integer sortType) throws NumberFormatException,
            ServiceException {

        Sort.Direction direction = Sort.Direction.DESC;
        if (SortTypeEnum.POSITIVE_SEQUENCE.getValue().equals(sortType)) {
            direction = Sort.Direction.ASC;
        }
        Pageable pageable = PageRequest.of(page, size, new Sort(direction, "gmtCreate"));
        RegShopIncomeDO regShopIncomeDo = new RegShopIncomeDO();
        regShopIncomeDo.setShopId(shopId);
        Page<RegShopIncomeDO> pageData = regShopIncomeRepository.findAll(
                Example.of(regShopIncomeDo), pageable);
        PageableShopIncomeDTO pageableShopIncomeDto = new PageableShopIncomeDTO();
        pageableShopIncomeDto.setTotalPages(pageData.getTotalPages());
        pageableShopIncomeDto.setTotalElements(pageData.getTotalElements());
        List<PageableShopIncomeDTO.ShopIncomeDTO> shopIncomeDTOList = new ArrayList<>();
        pageData.getContent();
        pageData.getContent().forEach(
                (recordDo) -> {
                    PageableShopIncomeDTO.ShopIncomeDTO shopIncomeDto = pageableShopIncomeDto.creatShopIncomeDTO();
                    BeanUtils.copyProperties(recordDo, shopIncomeDto);

                    // 查消费用户信息，项目信息
                    if (StringUtils.isNotBlank(shopIncomeDto.getOrderCode())) {
                        Optional<RegOrderDO> optional = Optional.ofNullable(regOrderRepository.findByOrderCode(shopIncomeDto.getOrderCode()));
                        try {
                            RegOrderDO orderDO = optional.orElseThrow(DBNullException::new);
                            UserOutDTO userDTO = userService.queryUser(orderDO.getUserId() + "").getData();
                            if (userDTO != null) {
                                com.kkwrite.regimen.provider.util.BeanUtils.copyProperties(userDTO, shopIncomeDto);
                            }
                            //查项目
                            ItemDetailDTO itemDetailDTO = itemService.getItemDetail(orderDO.getItemId());
                            if (itemDetailDTO != null) {
                                shopIncomeDto.setItemName(itemDetailDTO.getItemName());
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }

                    // 查店铺
                    ShopDetailDTO shopDetailDTO = getShopDetail(shopId);
                    if (shopDetailDTO != null) {

                        com.kkwrite.regimen.provider.util.BeanUtils.copyProperties(shopDetailDTO, shopIncomeDto);
                    }

                    shopIncomeDto.setCreateTime(recordDo.getGmtCreate().toLocalDateTime());
                    shopIncomeDTOList.add(shopIncomeDto);
                });
        pageableShopIncomeDto.setRecordList(shopIncomeDTOList);
        System.out.println("店铺收益明细List:" + pageableShopIncomeDto.toString());
        return pageableShopIncomeDto;
    }

    @Override
    @Transactional(rollbackFor = Exception.class, readOnly = false)
    public EditShopOutDTO editShop(EditShopInDTO editShopInDto) {
        Long shopId = editShopInDto.getShopId();
        if (shopId == null) {
            return new EditShopOutDTO("filed", "店铺ID没有找到");
        }


        RegShopDO regShopDOParam = new RegShopDO();
        regShopDOParam.setShopId(shopId);
        Optional<RegShopDO> regShopDOResult = regShopRepository.findOne(Example.of(regShopDOParam));
        RegShopDO regShopDo = regShopDOResult.orElseThrow(() -> new NullPointerException("该店铺没有相关信息"));

        /*BeanUtils.copyProperties(editShopInDto, regShopDo);*/
        com.kkwrite.regimen.provider.util.BeanUtils.copyProperties(editShopInDto, regShopDo);
        regShopRepository.saveAndFlush(regShopDo);
        //更新封面图
        //入参有封面地址的时候进行修改，否则跳过封面图修改步骤
        if (editShopInDto.getPictureUrl() != null) {
            RegPictureDO regPictureDoParam = new RegPictureDO();
            regPictureDoParam.setPictureOwnerId(shopId);
            //店铺
            regPictureDoParam.setPictureOwnerType((short) 1);
            // 封面图片
            regPictureDoParam.setPictureType((short) 11);
            RegPictureDO regPictureDO = regPictureRepository.findOne(Example.of(regPictureDoParam)).orElseThrow(RuntimeException::new);
            //之前有封面图，则进行修改
            regPictureDO.setPictureUrl(editShopInDto.getPictureUrl());
            regPictureRepository.saveAndFlush(regPictureDO);
        }
        return new EditShopOutDTO("success", "修改成功");
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public InsertShopOutDTO insertShop(EditShopInDTO editShopInDto) {
        RegShopDO regShopDo = new RegShopDO();
        com.kkwrite.regimen.provider.util.BeanUtils.copyProperties(editShopInDto, regShopDo);
        regShopDo.setShopKeywords(regShopDo.getShopName());
        regShopDo.setShopLevel((short) 5);
        int shopCount = regShopRepository.getShopCount();
        regShopDo.setShopOrder((float) (shopCount + 1));
        regShopDo.setDeleted((short) 0);
        regShopDo.setGmtCreate(new Timestamp(System.currentTimeMillis()));
        RegShopDO regShopDOResult = regShopRepository.saveAndFlush(regShopDo);
        if (editShopInDto.getPictureUrl() != null && regShopDOResult.getShopId() != null) {//入参有封面地址进行添加，否则跳过封面图修改步骤
            RegPictureDO regPictureDOInsert = new RegPictureDO();
            regPictureDOInsert.setPictureOwnerId(regShopDOResult.getShopId());
            regPictureDOInsert.setPictureOwnerType((short) 1);//店铺
            regPictureDOInsert.setPictureType((short) 11);//封面图片
            //添加封面图
            regPictureDOInsert.setPictureUrl(editShopInDto.getPictureUrl());
            regPictureDOInsert.setDeleted((short) 0);
            regPictureDOInsert.setGmtCreate(new Timestamp(System.currentTimeMillis()));
            regPictureRepository.saveAndFlush(regPictureDOInsert);
        }
        return new InsertShopOutDTO("success", regShopDOResult.getShopId(), "新增店铺成功");
    }

    @Override
    @Transactional(rollbackFor = Exception.class, readOnly = true)
    public String queryQrcodePath(String shopIdString) throws DBNullException {
        RegShopDO regShopDOParam = new RegShopDO();
        regShopDOParam.setShopId(Long.valueOf(shopIdString));
        Optional<RegShopDO> regShopDOResult = regShopRepository.findOne(Example.of(regShopDOParam));
        RegShopDO regShopDO = regShopDOResult.get();
        Optional<RegShopDO> optional = Optional.ofNullable(regShopDO);
        RegShopDO shop = optional.orElseThrow(DBNullException::new);
        return shop.getInviteQrcodePath();
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void saveQrcodePath(String accessQrcodePath, String shopId) throws DBNullException {
        RegShopDO regShopDOParam = new RegShopDO();
        regShopDOParam.setShopId(Long.valueOf(shopId));
        Optional<RegShopDO> regShopDOResult = regShopRepository.findOne(Example.of(regShopDOParam));
        RegShopDO regShopDO = regShopDOResult.get();
        Optional<RegShopDO> optional = Optional.ofNullable(regShopDO);
        RegShopDO shop = optional.orElseThrow(DBNullException::new);
        shop.setInviteQrcodePath(accessQrcodePath);
        regShopRepository.saveAndFlush(shop);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public InsertShopEmployeeOutDTO saveShopEmployee(InsertShopEmployeeInDTO inDto) {
        RegEmployeeDO regEmployeeDO = new RegEmployeeDO();
        com.kkwrite.regimen.provider.util.BeanUtils.copyProperties(inDto, regEmployeeDO);
        regEmployeeDO.setDeleted((short) 0);
        regEmployeeRepository.saveAndFlush(regEmployeeDO);
        return new InsertShopEmployeeOutDTO("success", "OK");
    }

}
